#!/usr/bin/env python3
"""
配置腾讯云COS的CORS设置
解决前端直接上传到COS时的跨域问题
"""

import json
import os
from qcloud_cos import CosConfig, CosS3Client
from qcloud_cos.cos_exception import CosServiceError

# COS配置
COS_SECRET_ID = os.getenv('COS_SECRET_ID', 'AKIDAQTJzVotlSwDH8p2MZw9E855uZHo8F9u')
COS_SECRET_KEY = os.getenv('COS_SECRET_KEY', 'jGav66wa9XkldKp9JI7kEdqulPq45vZ0')
COS_REGION = 'ap-beijing'
COS_BUCKET = 'photoenhancei-bj-1259206939'

def setup_cos_cors():
    """配置COS桶的CORS规则"""
    
    # 初始化COS客户端
    cos_config = CosConfig(
        Region=COS_REGION,
        SecretId=COS_SECRET_ID,
        SecretKey=COS_SECRET_KEY
    )
    cos_client = CosS3Client(cos_config)
    
    # CORS配置规则 - 简化版本，避免通配符问题
    cors_config = {
        'CORSRules': [
            {
                'AllowedOrigins': [
                    'https://www.gongjuxiang.work',
                    'https://gongjuxiang.work',
                    'http://localhost:3000',
                    'http://localhost:5173'
                ],
                'AllowedMethods': [
                    'GET',
                    'PUT',
                    'POST',
                    'HEAD',
                    'OPTIONS'
                ],
                'AllowedHeaders': [
                    'Content-Type',
                    'Content-MD5',
                    'Authorization'
                ],
                'ExposeHeaders': [
                    'ETag',
                    'x-cos-request-id'
                ],
                'MaxAgeSeconds': 3600
            }
        ]
    }
    
    try:
        # 设置CORS规则
        response = cos_client.put_bucket_cors(
            Bucket=COS_BUCKET,
            CORSConfiguration=cors_config
        )
        
        print(f"✅ CORS配置成功设置到桶: {COS_BUCKET}")
        print(f"📋 允许的域名:")
        for origin in cors_config['CORSRules'][0]['AllowedOrigins']:
            print(f"   - {origin}")
        print(f"🔧 允许的方法: {', '.join(cors_config['CORSRules'][0]['AllowedMethods'])}")
        print(f"📝 允许的请求头: {', '.join(cors_config['CORSRules'][0]['AllowedHeaders'])}")
        print(f"⏰ 预检请求缓存时间: {cors_config['CORSRules'][0]['MaxAgeSeconds']}秒")
        
        return True
        
    except CosServiceError as e:
        print(f"❌ CORS配置失败: {e.get_error_code()} - {e.get_error_msg()}")
        return False
    except Exception as e:
        print(f"❌ 配置过程中发生错误: {str(e)}")
        return False

def check_cors_config():
    """检查当前的CORS配置"""
    
    # 初始化COS客户端
    cos_config = CosConfig(
        Region=COS_REGION,
        SecretId=COS_SECRET_ID,
        SecretKey=COS_SECRET_KEY
    )
    cos_client = CosS3Client(cos_config)
    
    try:
        # 获取当前CORS配置
        response = cos_client.get_bucket_cors(Bucket=COS_BUCKET)
        
        print(f"📋 当前桶 {COS_BUCKET} 的CORS配置:")
        if 'CORSRules' in response:
            for i, rule in enumerate(response['CORSRules']):
                print(f"\n规则 {i+1}:")
                print(f"  允许的域名: {rule.get('AllowedOrigins', [])}")
                print(f"  允许的方法: {rule.get('AllowedMethods', [])}")
                print(f"  允许的请求头: {rule.get('AllowedHeaders', [])}")
                print(f"  暴露的响应头: {rule.get('ExposeHeaders', [])}")
                print(f"  预检请求缓存时间: {rule.get('MaxAgeSeconds', 0)}秒")
        else:
            print("  无CORS配置")
            
        return True
        
    except CosServiceError as e:
        if e.get_error_code() == 'NoSuchCORSConfiguration':
            print(f"📋 桶 {COS_BUCKET} 当前没有CORS配置")
        else:
            print(f"❌ 获取CORS配置失败: {e.get_error_code()} - {e.get_error_msg()}")
        return False
    except Exception as e:
        print(f"❌ 检查过程中发生错误: {str(e)}")
        return False

def main():
    """主函数"""
    print("🔧 腾讯云COS CORS配置工具")
    print("=" * 50)
    
    # 检查当前配置
    print("\n1. 检查当前CORS配置...")
    check_cors_config()
    
    # 设置CORS配置
    print("\n2. 设置CORS配置...")
    success = setup_cos_cors()
    
    if success:
        print("\n3. 验证配置...")
        check_cors_config()
        print("\n✅ CORS配置完成！前端现在应该可以正常上传到COS了。")
    else:
        print("\n❌ CORS配置失败，请检查网络连接和权限设置。")

if __name__ == "__main__":
    main()
